package com.sq.bootshiro.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sq.bootshiro.common.utils.JwtUtil;
import com.sq.bootshiro.common.utils.RedisUtil;
import com.sq.bootshiro.modules.entity.*;
import com.sq.bootshiro.modules.mapper.*;
import com.sq.bootshiro.modules.service.IShiroService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class ShiroServiceImpl implements IShiroService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleMapper roleRepository;
    @Autowired
    private PermissionMapper permissionRepository;
    @Autowired
    private SysTokenMapper sysTokenRepository;
    @Autowired
    private LogUserLoginMapper logUserLoginMapper;
    @Autowired
    private RedisUtil redisUtil;


    //12小时后失效
    private final static int EXPIRE = 12;
    //12小时换算成秒
    private final static int EXPIRESECOND = 12*60*60;

    @Override
    public User findUserByUsername(String username) {
        return userRepository.selectOne(new QueryWrapper<User>().eq("username",username));
    }

    @Override
    public User findUserByUserId(String id) {
        return userRepository.selectOne(new QueryWrapper<User>().eq("user_id",id));
    }

    @Override
    public Set<Role> findRolesByUserId(String userId) {
        Set<Role> roleListByUserId = roleRepository.findRoleListByUserId(userId);
        return roleListByUserId;
    }

    @Override
    public Set<Permission> findPermissionListByRoleId(String roleId) {
        Set<Permission> permissions = permissionRepository.findPermissionListByRoleId(roleId);
        return permissions;
    }

    @Override
    public SysToken findSysTokenByToken(String token) {
        return sysTokenRepository.selectOne(new QueryWrapper<SysToken>().eq("token",token));
    }

    @Override
    public Map<String, Object> createToken(String username,String password) {
        Map<String, Object> result = new HashMap<>();
        //由jwt生成一个token
        String token = JwtUtil.sign(username, password);

        //当前时间
        LocalDateTime now = LocalDateTime.now();
        //过期时间
        LocalDateTime expireTime = now.plusHours(EXPIRE);
        //判断是否生成过token

        redisUtil.set(username,token,EXPIRESECOND);
        result.put("token", token);
        result.put("expire", expireTime);
        return result;
    }

    @Override
    public void insertLogUserLogin(LogUserLogin logUserLogin) {
        logUserLoginMapper.insert(logUserLogin);
    }


    /**
     * 更新数据库的token，使前端拥有的token失效
     * 防止黑客利用token搞事情
     *
     * @param oldToken
     */
    @Override
    public void logout(String oldToken) {
        String username = JwtUtil.getUsername(oldToken);
        redisUtil.del(username);
    }


}
